<template>
  <el-dialog :visible="visible" :title="title" @close="close" width="56%" :close-on-click-modal="false">
    <el-form ref="form" :model="role" label-position="top">
        <el-col :span="24">
            <el-form-item
              label="角色名称"
              prop="role_name"
              :rules="[{ required: true, message: '请输入角色名称', trigger: 'blur' }]"
            >
              <el-input v-model="role.role_name" placeholder="请输入角色名称"  clearable />
            </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item
              label="角色描述"
              prop="role_desc"
              :rules="[{ required: true, message: '请输入角色描述', trigger: 'blur' }]"
            >
              <el-input v-model="role.role_desc" placeholder="请输入角色描述"  clearable />
            </el-form-item>
        </el-col>
    </el-form>
    <span slot="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { roleService } from '@/services';
export default {
  name: 'roleEdit',
  props: {
    operation: {
      default: 'add',
      validator: (value) => {
        return ['add', 'update'].indexOf(value) !== -1;
      },
    },
    visible: {
      type: Boolean,
      required: true,
    },
    role: {
      type: Object,
      required: true,
    },
  },
  computed: {
    title() {
      return this.operation === 'add' ? '添加角色' : '修改角色';
    },
  },
  methods: {
    close() {
      this.$emit('update:visible', false);
    },
    async confirm() {
      try {
        await this.$refs.form.validate();
        if(this.operation === 'add'){
           await roleService.addRole(this.role);
        }else {
          await roleService.editRole(this.role);
        }
        this.$emit('update:visible', false);
        this.$emit('confirm');
      } catch (e) {
        console.error(e);
      }
    }
  },
}
</script>